package jl.com.util;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DateUtil {
    /**
     * 将String字符串转换为java.sql.Timestamp格式日期,用于数据库保存
     *
     * @param strDate    表示日期的字符串
     * @param dateFormat 传入字符串的日期表示格式（如："yyyy-MM-dd HH:mm:ss"）
     * @return java.sql.Timestamp类型日期对象（如果转换失败则返回null）
     */
    public static java.sql.Timestamp strToSqlDate(String strDate, String dateFormat) {
        SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
        Date date = null;

        try {
            date = sf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        java.sql.Timestamp dateSQL = new java.sql.Timestamp(date.getTime());
        return dateSQL;
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param seconds 精确到秒的字符串
     * @param format
     * @return
     */
    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param seconds 精确到日的字符串
     * @param format
     * @return
     */
    public static String timeStamp2Date2(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }

    /**
     * 日期格式字符串转换成时间戳
     *
     * @param date_str 字符串日期
     * @param format   如：yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String date2TimeStamp(String date_str, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(date_str).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取多少天以前的日期,正数往后推,负数往前推
     *
     * @param day
     * @return long(时间戳)
     */
    public static String gtDateStr(int day) {
        Date date = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);//把日期往后增加一天.正数往后推,负数往前推
        date = calendar.getTime();   //这个时间就是日期往后推一天的结果
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String s = sf.format(date);
//        System.out.println("date="+s);//运行输出:date=2016-08-04 10:34:42
        Date s2 = strToSqlDate(s, "yyyy-MM-dd");
//        System.out.println(s2.getTime()/1000);
        Long l = s2.getTime() / 1000;
        return l.toString();
    }

    /**
     * 日期类型转换成String日期类型
     *
     * @param date
     * @return
     */
    public static String dateToStringDate(Date date) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = sf.format(date);
        return s;
    }

    /**
     * 随机等待
     *
     * @param time
     * @return
     */
    public static Integer returnDoubleTime(double time) {
        Double rr = (Double) (1 + Math.random() * (time - 1)) * 1000;
        return rr.intValue();
    }

    /*
     * 如果是小数，不保留，非小数，保留整数
     * @param number
     */
    public static String getDoubleString(double number) {
        String numberStr;
        if (((int) number * 1000) == (int) (number * 1000)) {
            //如果是一个整数
            numberStr = String.valueOf((int) number);
        } else {
            DecimalFormat df = new DecimalFormat("######0");
            numberStr = df.format(number);
        }
        return numberStr;
    }

    /**
     * 从string字符串中取出数字
     *
     * @param str
     * @return
     */
    public static String stringTakeNumber(String str) {
        str = str.trim();
        String str2 = "";
        if (str != null && !"".equals(str)) {
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                    str2 += str.charAt(i);
                }
            }
        }
        return str2;
    }

    /**
     * 取得当前时间戳（精确到秒）
     *
     * @return
     */
    public static String timeStamp() {
        long time = System.currentTimeMillis();
        String t = String.valueOf(time / 1000);
        return t;
    }


    /**
     * 返回昨天日期开始时间戳
     */
    public static String startTime(int number) {
        String dayLong = DateUtil.gtDateStr(number);//负数往前推 2019——2018，正数往后 2019——2020
        return dayLong;
    }

    /**
     * 返回昨天日期结束时间戳
     */
    public static String endTime(int number) {
        String dayLong = DateUtil.gtDateStr(number);//负数往前推 2019——2018，正数往后 2019——2020
        String day = DateUtil.timeStamp2Date2(dayLong, "");
        String dayTwoTwo = day + " 23:59:59";
        String dayTwo = DateUtil.date2TimeStamp(dayTwoTwo, "yyyy-MM-dd HH:mm:ss");
        return dayTwo;
    }

    /**
     * 根据参数，如参数为空返回null对象，否则变成一个带''  单引号的字符串
     * user表日期类型字符串专用
     *
     * @param date
     * @return
     */
    public static String rtnDate(String date) {
        String sOne = "'";
        String sTwo = "'";
        if (date == null || date.equals("0") || "".equals(date)) {
            sOne = null;
        } else {
            sOne += DateUtil.timeStamp2Date(date, "");
            sOne += sTwo;
        }
        return sOne;
    }

    /**
     * 品牌id数组分批
     *
     * @param brandIds 传入的品牌数组
     * @param munber   按此数量分组
     */
    public static List<String> rtnBrandIds(String[] brandIds, int munber) {

        List<String> stringList = new ArrayList<>();
        int result = (int) Math.floor(brandIds.length / munber);
        int count = 0;
        int rs = 0;
        for (int j = 0; j < result + 1; j++) {
            String str = "";
            rs = count;
            count += munber;
//            System.out.println("count:" + count + ",rs:" + rs);
            for (int i = 0; i < brandIds.length; i++) {
                if (j != result) {
                    if (i >= count) {
//                        System.out.println("str:" + str.substring(0,str.length()-1));
                        stringList.add(str.substring(0, str.length() - 1));
                        break;
                    }
                    if (i >= rs) {
                        str += brandIds[count - count + i] + ",";
                    }
                } else {
                    if (i >= result * munber) {
                        str += brandIds[count - count + i] + ",";
                        if (i == brandIds.length - 1) {
                            stringList.add(str.substring(0, str.length() - 1));
//                            System.out.println("str2:"+str.substring(0,str.length()-1));
                        }
                    }
                }
            }
        }
        return stringList;
    }

    /**
     * 获取当前时间距离凌晨12点的秒差
     * @return
     */
    public static Long getSecondsTobeforedawn() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        // 改成这样就好了
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }
}
